package com.tt.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.tt.reggie.common.BaseContext;
import com.tt.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否完成登录
 */

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        String requestURI = request.getRequestURI();

        //不需要拦截的请求
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };

        //判断是否放行
        boolean check = check(requestURI, urls);

        //如果不需要处理，则放行
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        //判断登录状态，如果已登录，则放行
        //管理端
        if(request.getSession().getAttribute("employee") != null){
            long id = Thread.currentThread().getId();
            filterChain.doFilter(request,response);
            return;
        }

        //移动端
        if(request.getSession().getAttribute("user") != null){
            Long uid = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(uid);
            long id = Thread.currentThread().getId();
            filterChain.doFilter(request,response);
            return;
        }
        //检测到未登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    //判断请求是否放行
    public boolean check(String requestURI,String[] urls){
        for (String url : urls){
            boolean match = PATH_MATCHER.match(url,requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }

}
